#!/usr/bin/perl

use strict;
use warnings;
use NetAddr::IP;

my $ip;
my $out_of_range = 0;

if (@ARGV > 1) {
    die('Too many arguments.\n');
}

if (defined($ARGV[0])) {
    $ip = $ARGV[0];    
} else {
    print "Enter an IP: ";
    chomp($ip = <STDIN>);
}

for(;;) {
    if ($ip !~ /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/) {
        print "Invalid IP. Try again: ";
        chomp($ip = <STDIN>);
        next;
    }
    my @arr = split(/\./,$ip);
    foreach my $oct (@arr) {
        if ($oct > 255) {
            $out_of_range = 1;
            last;
        }
    }
    if ($out_of_range == 1) {
        undef($out_of_range);
        $ip = 0;
        next;
    } else {
        last;
    }
}


my $range  = NetAddr::IP->new('0.0.0.0/0');
$ip = NetAddr::IP->new($ip);


if ($ip->within($range)) {
    printf "%s is within %s\n", $ip, $range;
} else {
    printf "%s is not within %s\n", $ip, $range;
}
